import Vue from 'vue'
import ToastContent from './ToastContent'
import PopupManager from 'element-ui/lib/utils/popup/popup-manager.js'
let container
let toastEl
function showToast (icon, msg, duration, top) {
  if (!toastEl) {
    let className = 'component-toast'
    toastEl = document.createElement('div')
    container = document.body
    toastEl.className = className
    toastEl.style.zIndex = PopupManager.nextZIndex()
    container.appendChild(toastEl)
  }
  let timestamp = (new Date()).getTime()
  const ToastContentClazz = Vue.extend(ToastContent)
  let toastContent = new ToastContentClazz({
    propsData: {
      icon,
      msg,
      duration,
      top,
      timestamp,
    },
  })
  toastContent.$mount()
  toastContent.$on('close', () => {
    destroyToast()
  })
  if (toastEl.firstChild && toastEl.firstChild.__vue__) {
    toastEl.firstChild.__vue__.$destroy(true)
  }
  toastEl.appendChild(toastContent.$el)
}

function destroyToast () {
  if (toastEl) {
    if (toastEl.firstChild && toastEl.firstChild.__vue__) {
      toastEl.firstChild.__vue__.$destroy(true)
    }
    container.removeChild(toastEl)
    toastEl = null
  }
}

const Toast = {
  show (msg, duration = 2, top = 80, icon = 'el-icon-info') {
    showToast(icon, msg, duration, top)
  },
  success (msg, duration, top) {
    Toast.show(msg, duration, top, 'el-icon-success')
  },
  warn (msg, duration, top) {
    Toast.show(msg, duration, top, 'el-icon-warning')
  },
  error (msg, duration, top) {
    Toast.show(msg, duration, top, 'el-icon-error')
  },
  close () {
    destroyToast()
  },
}

export default Toast
